package com.situ.web.controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.descriptor.web.LoginConfig;

import com.situ.web.entity.User;
import com.situ.web.service.IUserService;
import com.situ.web.service.impl.UserServiceImpl;
import com.situ.web.util.JSONResult;
import com.situ.web.util.JSONUtil;

@WebServlet("/user")
public class UserServlet extends HttpServlet{
	private IUserService userService = new UserServiceImpl();

	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String method = req.getParameter("method");
		switch (method) {
		case "login":
			login(req, resp);
			break;
		case "logout":
			logout(req, resp);
			break;

		default:
			break;
		}
	}

	private void logout(HttpServletRequest req, HttpServletResponse resp) throws IOException {
		HttpSession session = req.getSession(false);
		if (session != null) {
			session.invalidate();
			resp.sendRedirect(req.getContextPath() + "/login.jsp");
		}
	}

	private void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// 首先判断输入的验证码对不对，验证码不对，重新跳转到登录界面
		String checkCode = req.getParameter("checkCode");
		String checkCodeSession = (String) req.getSession().getAttribute("checkCodeSession");
//		if (checkCode == null 
//				|| "".equals(checkCode) 
//				|| !checkCode.equalsIgnoreCase(checkCodeSession)/* == false */) {
//			resp.sendRedirect(req.getContextPath() + "/login.jsp");
//			return;
//		}
		
		String name = req.getParameter("name");
		String password = req.getParameter("password");
		
		User user = userService.login(name, password);
//		if (user != null) {// 有这个用户，代表登录成功
//			// 把用户信息放到Session里面
//			HttpSession session = req.getSession();
//			session.setAttribute("user", user);
//			
//			resp.sendRedirect(req.getContextPath() + "/");
//		} else {
//			resp.sendRedirect(req.getContextPath() + "/fail.jsp");
//		}
		
		JSONResult jsonResult = null;
		if (user != null) {
			 //把用户信息放到Session里面
			HttpSession session = req.getSession();
			session.setAttribute("user", user);
			
			jsonResult = new JSONResult(JSONResult.OK, "登陸成功");
		} else {
			jsonResult = new JSONResult(JSONResult.ERROR, "登录失败");
		}
		
		JSONUtil.obj2Json(jsonResult, resp);
	}
}
